<?PHP
class SimpleIni {

	private $vars;
	private $file;

	public function __get($key) {
		return $this->vars[$key];
	}

	public function __set($key,$value) {
		$this->vars[$key];
	}

	private function check_file() {
		return
			is_writable($this->file) ||
			(is_writable(dirname($this->file)) && !file_exists($this->file));
	}

	public function __construct($file,$defaults) {
		$this->file = $file;
		if(!$this->check_file()) {
			$this->vars = $defaults;
			return;
		}
		touch($this->file);
		$this->vars = array_merge($defaults,parse_ini_file($file));
	}

	public static function create_with_defaults($file,$defaults) {
		return new self($file,$defaults);
	}

	public static function create($file) {
		return self::create_with_defaults($file,array());
	}

	public function write() {
		// don't save changes if you can't.
		if(!$this->check_file())
			return;
		// else write the entire ini file
		$fp = fopen($file);
		function write_kv($k,$v) {
			if(is_string($v))
				$v = '"'.$v.'"';
			fwrite($fp,$k.' = '.$v."\r\n");
		}
		foreach ($this->vars as $key => $val) { 
			if (is_array($val))
				foreach($val as $sub)
					write_kv($key.'[]',$sub);
			else
				write_kv($key,$val);
		}
	}

}
?>
